package demo1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-03-20
 * Time: 15:44
 */
public class SeqList {
    private int[] array;//存放数据的数组
    private int size;//当前的长度
    private final int capacity;//容量

    public SeqList(int capacity) {
        this.capacity = capacity;
        this.array = new int[this.capacity];
        this.size = 0;
    }

    public void add(int data) {
        //在最后位置添加数据
        if (this.size == this.capacity) {
            return;
        }
        this.array[this.size] = data;
        this.size++;
    }

    public void add(int data, int pos) {
        //在pos位置添加数据
        if ((pos < 0 || pos >= capacity) && this.size == this.capacity) {
            return;
        }
        int cur = this.size;
        while (cur > pos) {
            this.array[cur] = this.array[cur - 1];
            cur--;
        }
        this.array[pos] = data;
        this.size++;
    }

    public boolean contains(int num) {
        //判断num是不是在表中
        for (int i = 0; i < size; i++) {
            if (this.array[i] == num) {
                return true;
            }
        }
        return false;
    }

    public int indexOf(int num) {
        //返回num的下标
        for (int i = 0; i < size; i++) {
            if (this.array[i] == num) {
                return i;
            }
        }
        return -1;
    }

    public int get(int pos) {
        //获取pos位置的数据
        if (pos < -1 || pos > capacity) {
            System.out.println("非法下标!!!!");
            System.exit(1);
        }
        return this.array[pos];
    }

    public void set(int pos, int value) {
        //将pos位置设置为value
        if (pos < -1 || pos > capacity) {
            System.out.println("非法下标!!!!");
            System.exit(1);
        }
        this.array[pos] = value;
    }

    public void remove(int num) {
        //移除第一次出现的num
        for (int i = 0; i < size; i++) {
            int cur = i;
            if (this.array[i] == num) {
                //挪
                while (cur < size - 1) {
                    this.array[cur] = this.array[cur + 1];
                    cur++;
                }
                this.size--;
                return;
            }
        }
    }

    public int size() {
        //获取顺序表长度
        return this.size;
    }

    public void clear() {
        //清空顺序表
        this.array = null;
    }

    public void display() {
        //打印顺序表
        System.out.print("[");
        for (int i = 0; i < this.size; i++) {
            if (i != 0) {
                System.out.print("," + this.array[i]);
            } else {
                System.out.print(this.array[i]);
            }

        }
        System.out.print("]");
//        System.out.println(Arrays.toString(this.array));
        System.out.println();
    }
}